import Icon from "@/components/Icon";
import { store } from "@/redux";
import { Modal, Upload, UploadFile } from "antd";
import { RcFile, UploadProps } from "antd/lib/upload";
import { useState } from "react";
const getBase64 = (file: RcFile): Promise<string> =>
	new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result as string);
		reader.onerror = error => reject(error);
	});
const index = ({ certUrl }: any) => {
	//上传图片
	const [previewOpen, setPreviewOpen] = useState(false);
	const [previewImage, setPreviewImage] = useState("");
	const [previewTitle, setPreviewTitle] = useState("");
	const [fileList, setFileList] = useState<UploadFile[]>([]);
	const handleCancel = () => setPreviewOpen(false);

	const handlePreview = async (file: UploadFile) => {
		if (!file.url && !file.preview) {
			file.preview = await getBase64(file.originFileObj as RcFile);
		}
		setPreviewImage(file.url || (file.preview as string));
		setPreviewOpen(true);
		setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf("/") + 1));
	};

	const handleChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
		certUrl(newFileList);
		return setFileList(newFileList);
	};
	const uploadButton = (
		<div>
			<Icon icon="ant-design:plus-outlined" />
			<div style={{ marginTop: 8 }}></div>
		</div>
	);
	return (
		<div>
			<Upload
				action={`${import.meta.env.VITE_API_URL as string}/infra/file/upload`}
				headers={{ Authorization: `Bearer ${store.getState().user.accessToken}` }}
				listType="picture-card"
				fileList={fileList}
				onPreview={handlePreview}
				onChange={handleChange}
			>
				{fileList.length >= 1 ? null : uploadButton}
			</Upload>
			<Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
				<img alt="example" style={{ width: "100%" }} src={previewImage} />
			</Modal>
		</div>
	);
};
export default index;
